<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 添加角色 -->
      <el-row :gutter="10">
        <el-col :span="3">
          <el-button type="primary" @click="showAddSoleDialog(-1)">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rulesDataList" style="width: 100%" stripe border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 一级权限 -->
            <el-row
              :class="['borderB',i1 === 0 ? 'borderT' : '','el-row-child']"
              v-for="(item,i1) in scope.row.children"
              :key="i1"
              :gutter="10"
            >
              <el-col :span="5">
                <el-tag closable @close="deleteSoleRight(scope.row,item.id)">{{ item.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'borderT','el-row-child']"
                  v-for="(item2,i2) in item.children"
                  :key="i2"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="deleteSoleRight(scope.row,item2.id)"
                    >{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="13">
                    <el-tag
                      v-for="(item3,i3) in item2.children"
                      :key="i3"
                      type="warning"
                      closable
                      @close="deleteSoleRight(scope.row,item3.id)"
                    >{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showAddSoleDialog(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteSole(scope.row.id)"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showRightsDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色的dialog弹窗 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addSoleDialogVisible"
      width="50%"
      @close="addSoleDialogClosed"
    >
      <el-form
        ref="addSoleFormRef"
        :rules="addSoleFormRules"
        :model="addSoleForm"
        label-width="100px"
      >
        <el-form-item prop="roleName" label="角色名称：">
          <el-input v-model="addSoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item prop="roleDesc" label="角色描述：">
          <el-input v-model="addSoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addSoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSoleData">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="分配权限" :visible.sync="isDialogVisible" width="50%" @close="rightsDialogClosed">
      <el-tree
        ref="treeRef"
        :data="rightsList"
        node-key="id"
        default-expand-all
        :props="defaultProps"
        show-checkbox
        :default-checked-keys="exisRight"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="rightsOK">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.reqSolesData();
  },
  data() {
    return {
      rulesDataList: [],
      addSoleDialogVisible: false,
      isDialogVisible: false,
      // 添加角色表单数据
      addSoleForm: {
        id: -1,
        roleName: "",
        roleDesc: ""
      },

      // 修改角色表单数据
      editSoleForm: {
        id: 0,
        roleName: "",
        roleDesc: ""
      },

      //添加角色的数据验证
      addSoleFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在2到8个字符", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 2, max: 8, message: "长度在5到8个字符", trigger: "blur" }
        ]
      },
      roleId: "",
      // 分配权限的数据列表
      rightsList: [],
      // 分配权限显示的key
      defaultProps: {
        children: "children",
        label: "authName"
      },
      //角色已有的权限id数组
      exisRight: []
    };
  },
  methods: {
    //请求角色列表
    reqSolesData() {
      this.$httpReq.get("roles").then(res => {
        if (res.meta.status == 200) {
          this.rulesDataList = res.data;
        } else {
          var msg = res.meta.msg;
          this.$message.error(msg);
        }
      });
    },
    //请求权限列表
    reqRightsData() {
      this.$httpReq.get("rights/tree").then(res => {
        if (res.meta.status == 200) {
          this.rightsList = res.data;
        } else {
          var msg = res.meta.msg;
          this.$message.error(msg);
        }
      });
    },
    //请求分配权限
    reqSetRights(arrId) {
      console.log('分配权限==>' + arrId.size + "====<" + !arrId);
      if(!arrId || arrId.size === 0) return  this.$message.error("请选择要分配的权限");
      this.$httpReq
        .post(`roles/${this.roleId}/rights`, { rids: arrId })
        .then(res => {
           var msg = res.meta.msg;
            if (res.meta.status == 200) {
              this.$message.success("权限分配成功");
              this.isDialogVisible = false; 
              this.reqSolesData();
            } else {
              this.$message.error(msg);
            }
        })
        .catch(err => {
          this.$message.error(err);
        });
    },

    //显示添加角色弹窗
    showAddSoleDialog(data) {
      if (data == -1) {
        console.log("点击添加角色");
        this.addSoleForm.id = data;
      } else {
        console.log("点击编辑角色");
        this.addSoleForm.id = data.id;
        this.addSoleForm.roleName = data.roleName;
        this.addSoleForm.roleDesc = data.roleDesc;
      }
      this.addSoleDialogVisible = true;
    },
    //添加角色弹窗的关闭监听
    addSoleDialogClosed() {
      this.$refs.addSoleFormRef.resetFields();
    },
    //确认添加角色数据
    addSoleData() {
      this.$refs.addSoleFormRef.validate(valid => {
        console.log("确认角色数据==>" + valid);
        if (this.addSoleForm.id == -1) {
          this.$httpReq
            .post("roles", this.addSoleForm)
            .then(res => {
              // {"data":{"roleId":42,"roleName":"aaa","roleDesc":"aaa"},"meta":{"msg":"创建成功","status":201}}
              console.log("添加角色===>" + JSON.stringify(res));
              var msg = res.meta.msg;
              if (res.meta.status == 201) {
                this.$message.success("添加角色成功");
                this.reqSolesData();
                this.addSoleDialogVisible = false;
              } else {
                this.$message.error(msg);
              }
            })
            .catch(err => err);
        } else {
          this.$httpReq
            .put(`roles/${this.addSoleForm.id}`, this.addSoleForm)
            .then(res => {
              // {"data":{"roleId":42,"roleName":"aaa","roleDesc":"aaa"},"meta":{"msg":"创建成功","status":201}}
              console.log("修改角色===>" + JSON.stringify(res));
              var msg = res.meta.msg;
              if (res.meta.status == 200) {
                this.$message.success("修改角色成功");
                this.reqSolesData();
                this.addSoleDialogVisible = false;
              } else {
                this.$message.error(msg);
              }
            })
            .catch(err => err);
        }
      });
    },
    //删除角色
    deleteSole(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$httpReq
            .delete(`roles/${id}`)
            .then(res => {
              var msg = res.meta.msg;
              if (res.meta.status == 200) {
                this.$message.success("删除角色成功");
                this.reqSolesData();
              } else {
                this.$message.error(msg);
              }
            })
            .catch(err => {
              this.$message.error(err);
            });
        })
        .catch(err => {
          console.log(err);
          this.$message("取消删除成功！");
        });
    },
    // 删除角色权限
    deleteSoleRight(data, id) {
      this.$confirm("此操作将永久删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$httpReq
            .delete(`roles/${data.id}/rights/${id}`)
            .then(res => {
              var msg = res.meta.msg;
              if (res.meta.status == 200) {
                this.$message.success("删除角色权限成功");
                data.children = res.data;
              } else {
                this.$message.error(msg);
              }
            })
            .catch(err => this.$message(err));
        })
        .catch(err => {
          console.log(err);
          this.$message("取消删除权限");
        });
    },
    //显示分配权限弹窗
    showRightsDialog(data) {
      this.roleId = data.id;
      this.getExisRights(data, this.exisRight);
      this.reqRightsData();
      this.isDialogVisible = true;
    },
    //递归获取当前角色已有 的权限
    getExisRights(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach(item => {
        this.getExisRights(item, arr);
      });
    },
    //权限分配弹窗 关闭监听
    rightsDialogClosed() {
      this.exisRight = [];
    },
    //确认分配权限
    rightsOK() {
      const selectArr = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      console.log(selectArr);
      const newArr = selectArr.join(",");
      console.log(newArr);
      this.reqSetRights(newArr);
    }
  }
};
</script>

<style>
.el-tag {
  margin: 7px;
}
.el-row-child {
  display: flex;
  align-items: center;
}
.borderT {
  border-top: 1px solid #eee;
}
.borderB {
  border-bottom: 1px solid #eee;
}
</style>